package com.cloudcc.mobile.view.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.cloudcc.cloudframe.CApplication;
import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.entity.UpdateImage;
import com.cloudcc.mobile.entity.UserBasicInfoForUpdate;
import com.cloudcc.mobile.manager.UserManager;
import com.cloudcc.mobile.util.ImageUtils;
import com.cloudcc.mobile.util.Json;
import com.cloudcc.mobile.util.NetWork;
import com.cloudcc.mobile.util.Tools;
import com.cloudcc.mobile.util.UrlTools;
import com.cloudcc.mobile.util.UserUtils;
import com.cloudcc.mobile.view.base.BaseActivity;
import com.cloudcc.mobile.weight.CustomProgressDialog;
import com.litesuits.android.log.Log;
import com.mypage.utils.SaveTemporaryData;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 修改我的信息
 *
 * @author Administrator
 */
public class UpdateInfoActivity extends BaseActivity {
    @Bind(R.id.editHeaderImg)
    ImageView editHeaderImg;
    @Bind(R.id.userName)
    TextView userName;
    @Bind(R.id.userStr)
    TextView userStr;
    private Button fanhui;
    private Button save;
    private EditText me_address, me_mobile, me_phone, me_email;
    private String email = "";
    private String photo = "";
    private String mobile = "";
    private String xingming = "";
    private String about = "";
    private UserBasicInfoForUpdate mUserBasicInfo;
    private CustomProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        try {
            setupView();//修改
            addListener();
            setData();
            setHeaderImg();
        } catch (Exception e) {
            Tools.handle(e);
        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.update_info;
    }

    //判断email格式是否正确
    public boolean isEmail(String email) {
        String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
        Pattern p = Pattern.compile(str);
        Matcher m = p.matcher(email);
        return m.matches();
    }

    /**
     * 获取控件
     */
    private void setupView() {
        fanhui = (Button) findViewById(R.id.fanhui_guanyuwo);
        save = (Button) findViewById(R.id.saveinfo);
        me_email = (EditText) findViewById(R.id.me_email);
        me_phone = (EditText) findViewById(R.id.me_phone);
        me_mobile = (EditText) findViewById(R.id.me_mobile);
        //address修改为name
        me_address = (EditText) findViewById(R.id.me_xingming);
//		me_about=(EditText)findViewById(R.id.me_about);

    }

    private void setData() {
        mUserBasicInfo = (UserBasicInfoForUpdate) getIntent().getSerializableExtra("chatuser");

        me_email.setText(SaveTemporaryData.aboutEmail);
        me_phone.setText(SaveTemporaryData.aboutNumber);
        me_mobile.setText(SaveTemporaryData.aboutMobile);
        me_address.setText(mUserBasicInfo.getAddress());


//        me_email.setText(mUserBasicInfo.getEmail());
//        me_phone.setText(mUserBasicInfo.getPhone());
//        me_mobile.setText(mUserBasicInfo.getMobile());
//        me_address.setText(mUserBasicInfo.getAddress());


//		me_about.setText(mUserBasicInfo.getAbout());
//       setHeaderImg();
    }

    public void setHeaderImg() {
        //头像
        String userId = UserManager.getManager().getUser().userId;
        String url = UrlTools.getTopImage(userId);
        UserUtils.setLogoRound_z(url, editHeaderImg,
                UserUtils.getBackGroudColorByUserIdHash(userId, this),
                UserUtils.getNickRowName(mUserBasicInfo.getName()), this);
        //
        userName.setText(mUserBasicInfo.getName());
        userName.setTextColor(Color.rgb(36,62,101));
        userStr.setText(CApplication.juese + " | " + CApplication.jiandang);
        userStr.setTextColor(Color.rgb(119,134,165));
    }

    private void addListener() {
        save.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                updateData();
            }
        });
        fanhui.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                UpdateInfoActivity.this.finish();
            }
        });
    }

    protected void updateData() {
        email = me_email.getText().toString().trim();
        photo = me_phone.getText().toString().trim();
        mobile = me_mobile.getText().toString().trim();
        xingming = me_address.getText().toString().trim();

//        if (!isPhone(photo)) {
//
//            if (photo.length()>11){
//                Toast.makeText(UpdateInfoActivity.this, R.string.quhaodianhuahaoma, Toast.LENGTH_SHORT).show();
//                return;
//            }
//
//            Toast.makeText(this, R.string.dian_huag, Toast.LENGTH_SHORT).show();
//            return;
//        }
//        if (!isMobileNO(mobile)) {
//            Toast.makeText(this, R.string.mobilegeshicuowu, Toast.LENGTH_SHORT).show();
//            return;
//        }
        if ("".equals(email)) {
            Toast.makeText(UpdateInfoActivity.this, R.string.yzyouxiangk, 1).show();
            return;
        } else if (!isEmail(email)) {
            Toast.makeText(UpdateInfoActivity.this, R.string.yxgs, 1).show();
            return;
        }
//		about=me_about.getText().toString().trim();
        new UpdateDataTask().execute();


//        Intent intent = new Intent();
//        intent.putExtra("Email", email);
//        intent.putExtra("Number", photo);
//        intent.putExtra("Mobile", mobile);
//        intent.putExtra("smart", 1);
//        this.setResult(101, intent);
//        UpdateInfoActivity.this.finish();
    }

    /**
     * 修改数据
     */
    class UpdateDataTask extends AsyncTask<Void, Void, String> {
        @Override
        protected void onPreExecute() {
            showWainting();
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(Void... arg0) {
            String result = "";
            try {
                String bitmapToBase64;
                if (mUserBasicInfo.getImg() == null) {
                    bitmapToBase64 = "";
                } else {
                    bitmapToBase64 = ImageUtils.bitmapToBase64(ImageUtils.Bytes2Bimap(mUserBasicInfo.getImg()));
                }
                UpdateImage upimage = new UpdateImage(email, "", photo, mobile,
                        about, "", xingming, "", mUserBasicInfo.getTitle());
                String data = Json.toJson(upimage);
                List<NameValuePair> pairs = new ArrayList<NameValuePair>();
                pairs.add(new BasicNameValuePair("serviceName", "updateChatterUserInfo"));
                pairs.add(new BasicNameValuePair("data", data));
                pairs.add(new BasicNameValuePair("binding", AppContext.binding));
                String url = UrlTools.url + UrlTools.postpath;
                result = NetWork.post(url, pairs);
                Log.d("request",url+"?serviceName=updateChatterUserInfo&data="+data+"&binding="+AppContext.binding);
                return result;
            } catch (Exception e) {
                Tools.handle(e);
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            try {
                dismissWainting();
                if (result == null) {
                    Toast.makeText(mContext, "修改信息失败", 1).show();
                    UpdateInfoActivity.this.finish();
                    return;
                } else {
                    JSONObject json = new JSONObject(result);
                    boolean isResult = json.getBoolean("result");
                    if (isResult) {
                        onSaveSuccess();
                    } else {
                        Toast.makeText(mContext, "修改信息失败", 1).show();
                        return;
                    }
                }
            } catch (JSONException e) {
                Tools.handle(e);
            }
            super.onPostExecute(result);
        }
    }

    private void onSaveSuccess() {
        mUserBasicInfo.setEmail(email);
        mUserBasicInfo.setPhone(photo);
        mUserBasicInfo.setMobile(mobile);
        mUserBasicInfo.setAddress(xingming);
        mUserBasicInfo.setAbout(about);
        Intent data = new Intent();
        data.putExtra("user.new", mUserBasicInfo);
        setResult(RESULT_OK, data);
        succIntent();
        finish();
    }

    public void succIntent() {
        Intent intent = new Intent();
        intent.putExtra("Email", email);
        intent.putExtra("Number", photo);
        intent.putExtra("Mobile", mobile);
        intent.putExtra("smart", 1);
        this.setResult(101, intent);
        SaveTemporaryData.aboutEmail = email;
        SaveTemporaryData.aboutNumber = photo;
        SaveTemporaryData.aboutMobile = mobile;
        UpdateInfoActivity.this.finish();
    }

    public boolean isMobileNO(String mobiles) {


        Pattern p = Pattern.compile("^((13[0-9])|(14[0-9])|(15[^4,\\D])|(18[0,5-9])|(17[0-9]))\\d{8}$");


        Matcher m = p.matcher(mobiles);


        return m.matches();


    }

    /**
     * 电话号码验证
     *
     * @param str
     * @return 验证通过返回true
     * @author ：shijing
     * 2016年12月5日下午4:34:21
     */
    public static boolean isPhone(final String str) {
        String strr = str;
        if (str.length() == 11) {
            strr = str.substring(4, str.length());
        }
        if (str.length() == 10) {
            strr = str.substring(3, str.length());
        }

        Pattern p1 = null, p2 = null;
        Matcher m = null;
        boolean b;
        p1 = Pattern.compile("^[0][1-9]{2,3}-[0-9]{5,10}$");  // 验证带区号的
        p2 = Pattern.compile("^[1-9]{1}[0-9]{5,8}$");         // 验证没有区号的
        if (strr.length() > 9) {
            m = p1.matcher(strr);
            b = m.matches();
        } else {
            m = p2.matcher(strr);
            b = m.matches();
        }
        return b;
    }
}
